//https://www.aiscore.com/
var currentUrl = location.href

var dateList = getDateList()
var match = currentUrl.match(/aiscore\.com\/([a-zA-Z]+\/)?(\d{8})$/);

if (match && dateList.includes(match[2])) {
    message('采集主页。。。', 'success')
    
    function collect() {
        const links = document.querySelectorAll('a.match-container');
        const hrefs = Array.from(links).map(link => link.href);
        return hrefs
    }

    async function run () {
        console.log('start...')
        // await sleep(1000);
        let list = []
        let i = 0
        let clickScheduled = false
        let reach = false
        let list_count = 0
        let limit = 0 //25次list数量没变化后就当作到底了。
        while (true) {
            //判断当前是不是英文，如果不是就选择英文
            var node = getElementByXpath('//span[contains(@class,"signIn")]');
            if (!node) continue
            if (node.innerText != 'Sign in') {
                //弹窗选择语言窗口
                var node = getElementByXpath('//span[contains(@class,"moreOption")]');
                if (!node) continue
                await sleep(1000)
                node.click()
                //点击下拉框
                var node = getElementByXpath('//div[@class="languageListBox"]');
                if (!node) continue
                await sleep(1000)
                node.click()
                //选择英语
                var node = getElementByXpath('//div[@class="languageList"]//p[text()="English"]');
                if (!node) continue
                await sleep(1000)
                node.click()
                break;

            }
            //切换到Scheduled
            if (!clickScheduled) {
                var node = getElementByXpath('//span[contains(text(),"Scheduled") and contains(@class,"changeItem")]')
                if (!node) continue
                if (node) {
                    await sleep(200);
                    node.click()
                    clickScheduled = true
                }
            }

            await sleep(200)
            var data = collect()
            if (data.length == 0) continue  
            list = list.concat(data)
            list = Array.from(new Set(list)) // 去重

            if (Math.ceil(window.scrollY)+Math.ceil(window.innerHeight)>=document.documentElement.scrollHeight) {
                console.log('到底了')
                break;
            } else {
                if (list.length == list_count) {
                    limit++
                } else {
                    list_count = list.length
                    limit = 0
                }
                if (limit > 25) {
                    console.log('到底了'+limit)
                    break;
                }
                console.log('Math.ceil(window.scrollY)+Math.ceil(window.innerHeight)='+(Math.ceil(window.scrollY)+Math.ceil(window.innerHeight)))
                console.log('document.documentElement.scrollHeight='+document.documentElement.scrollHeight)
                console.log('没有到底：'+(Math.ceil(window.scrollY)+Math.ceil(window.innerHeight)>=document.documentElement.scrollHeight))
            }
            i++
            window.scrollTo(0, i*(window.innerHeight-100));
        }

        for (let i=0;i<list.length;i++) {
            list[i] = list[i].replace(/\/h2h$/, '/odds')
        }

        console.log("链接数量",list.length)
        chrome.storage.local.set({
            urls: list,
            date: match[2]
        });
        await sleep(500)

        jumpCollectPage()
    }

    addLoadEvent(run)
} else if ( (/aiscore\.com\/match\-(.+?)\/(.+?)\/odds/i).test(currentUrl) ) {
    message('采集详情页。。。', 'success')

    function getColumnText(xpath) {
        let val = ''
        for (let row=1; row <= 4; row++) {
            let node = getElementByXpath(xpath.replace('%s', row))
            let newVal = node ? node.innerText : ''
            if (val === '') {
                val = newVal
            }
            if (newVal!=='' && newVal!=='-') {
                val = newVal
                break
            }
        }
        return val
    }
    function getData() {
        let node = ''
        node = getElementByXpath('//*[@itemprop="homeTeam"]')
        let home_team = node ? node.innerText : ''
        if (!home_team) return null;

        node = getElementByXpath('//*[@itemprop="awayTeam"]')
        let away_team = node ? node.innerText : ''
        if (!away_team) return null;

        node = getElementByXpath('//h1[@itemprop="name"]')
        let date = node ? node.innerText.replace(/\/+/g, '').substring(0,8) : ''
        if (!date) return null;

        //判断是否有数据
        let no_data = getElementByXpath('//div[text()="No data"]') ? true : false

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[1]/div[2]/div/div[1]')
        // let _1 = node ? node.innerText : ''
        // if (!_1 && !no_data) return null;
        let _1 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[1]/div[2]/div/div[1]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[1]/div[2]/div/div[2]')
        // let x = node ? node.innerText : ''
        // if (!x && !no_data) return null;
        let x = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[1]/div[2]/div/div[2]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[1]/div[2]/div/div[3]')
        // let _2 = node ? node.innerText : ''
        // if (!_2 && !no_data) return null;
        let _2 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[1]/div[2]/div/div[3]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[2]/div[2]/div/div[1]//span[contains(@class, "asiaItemLeft")]')
        // let a = node ? node.innerText : ''
        // if (!a && !no_data) return null;
        let a = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[2]/div[2]/div/div[1]//span[contains(@class, "asiaItemLeft")]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[2]/div[2]/div/div[1]//span[contains(@class, "asiaItemRight")]')
        // let a0 = node ? node.innerText : ''
        // if (!a0 && !no_data) return null;
        let a0 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[2]/div[2]/div/div[1]//span[contains(@class, "asiaItemRight")]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[2]/div[2]/div/div[2]//span[contains(@class, "asiaItemRight")]')
        // let a1 = node ? node.innerText : ''
        // if (!a1 && !no_data) return null;
        let a1 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[2]/div[2]/div/div[2]//span[contains(@class, "asiaItemRight")]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[3]/div[2]/div/div[1]')
        // let b = node ? node.innerText : ''
        // if (!b && !no_data) return null;
        let b = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[3]/div[2]/div/div[1]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[3]/div[2]/div/div[2]')
        // let b0 = node ? node.innerText : ''
        // if (!b0 && !no_data) return null;
        let b0 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[3]/div[2]/div/div[2]')

        // node = getElementByXpath('//*[@class="content"]/div[1]/div[2]/div/div[3]/div[2]/div/div[3]')
        // let b1 = node ? node.innerText : ''
        // if (!b1 && !no_data) return null;
        let b1 = getColumnText('//*[@class="content"]/div[%s]/div[2]/div/div[3]/div[2]/div/div[3]')

        //放到一个数组里
        if (!no_data && !_1 && !x && !_2 && !a && !a0 && !a1 && !b && !b0 && !b1) {
            return null
        }
        let data = {url:currentUrl,home_team,away_team,date,_1,x,_2,a,a0,a1,b,b0,b1}

        return data
    }

    async function run () {
        console.log('Start...')
        let i = 0;
        while (true) {
            let data = getData()
            if (data) {
                console.log(data)
                //插入数据库
                sendMessageToBackground('insertData', data, res=>{
                    message(res.msg, res.code == 1 ? 'success' : 'error')
                })
                break;
            }
            await sleep(200)
            //最多25*0.2=5s加载不出来直接跳走
            i++
            if (i>=25) break;
        }
        console.log('End')
        //await sleep(100)
        //window.close();
        jumpCollectPage()
    }
    
    run()
} else {
    location.href = "https://www.aiscore.com/"+dateList[0]
}